package com.jnu.accounthelper.ui.slideshow;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.jnu.accounthelper.EditAccountActivity;
import com.jnu.accounthelper.R;
import com.jnu.accounthelper.databinding.FragmentAccountBinding;
import com.jnu.accounthelper.db.Account;
import com.jnu.accounthelper.db.DBManager;
import com.jnu.accounthelper.ui.home.HomeFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AccountFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AccountFragment extends Fragment {
    private SlideshowViewModel slideshowViewModel;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String mParam3;
    
    private HashMap<String,Integer> hash= new HashMap<>();
    public static final int RESULT_CODE_ADD_DATA = 996;
    private TextView textView;

    private FragmentAccountBinding binding;
    private RecyclerView recyclerView;
    private ImageButton fab;
    private ArrayList<Account> accounts;
    private PieChart mPieChart;
    private MyRecyclerViewAdapter adapter;
    Date startTime = new Date();
    Date endTime = new Date();
    // TODO: Rename and change types of parameters

    private RadioButton last;
    public AccountFragment() {
        // Required empty public constructor
    }

    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){


            }
        }
    });
    // TODO: Rename and change types and number of parameters

    public static AccountFragment newInstance(String param1, String param2, String param3) {
        AccountFragment fragment = new AccountFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, param3);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            mParam3 = getArguments().getString(ARG_PARAM3);
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        slideshowViewModel =
                new ViewModelProvider(this).get(SlideshowViewModel.class);
        slideshowViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                Log.d("传递数据",s);
            }
        });

        hash.put("微信",R.drawable.wechat);
        hash.put("支付宝",R.drawable.zhifubao);
        hash.put("银行卡",R.drawable.card);
        hash.put("现金",R.drawable.cash);

        binding = FragmentAccountBinding.inflate(inflater, container, false);
        View root = inflater.inflate(R.layout.fragment_account, container, false);
        setAccounts();
        textView=root.findViewById(R.id.title);


        fab=root.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater li = LayoutInflater.from(AccountFragment.this.getContext());
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        AccountFragment.this.getContext());

                AlertDialog alertDialog;
                View deleteView =LayoutInflater.from(AccountFragment.this.getContext()).inflate(R.layout.comtemlayout,null);
                LinearLayout dynamic;
                //自定义时间段
                TimePickerView pvTime=new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        //如果是开始时间的EditText
                        if(v.getId() == R.id.et_startTime){
                            startTime = date;
                        }else {
                            endTime = date;
                        }
                        EditText editText = (EditText)v;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                        editText.setText(sdf.format(date));
                    }
                })
                        .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                            @Override
                            public void onTimeSelectChanged(Date date) {

                            }
                        })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .isDialog(true)
                        .build();


                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                };
                dynamic=deleteView.findViewById(R.id.dynamic);
                EditText et_startTime=deleteView.findViewById(R.id.et_startTime);
                et_startTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (pvTime != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(startTime);
                            pvTime.setDate(calendar);
                            pvTime.show(v);
                        }
                    }
                });

                EditText et_endTime=deleteView.findViewById(R.id.et_endTime);
                et_endTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (pvTime != null) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(startTime);
                            pvTime.setDate(calendar);
                            pvTime.show(v);
                        }
                    }
                });
                //last.setChecked(true);
                RadioGroup radioGroup1= (RadioGroup) deleteView.findViewById(R.id.radio_group1);
                    /*if(last!=null)
                        last.setChecked(true);*/
                radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        int radioButtonId = group.getCheckedRadioButtonId();
                        RadioButton rb = (RadioButton)deleteView.findViewById(radioButtonId);
                        mParam2=rb.getText().toString();
                    }
                });


                RadioGroup radioGroup2= (RadioGroup) deleteView.findViewById(R.id.radio_group2);
                mParam3="本月";
                radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        int radioButtonId = group.getCheckedRadioButtonId();
                        RadioButton rb = (RadioButton)deleteView.findViewById(radioButtonId);
                        last=rb;

                        mParam3=rb.getText().toString();
                        if(mParam3.equals("自定义")){
                            dynamic.setVisibility(View.VISIBLE);
                        }

                    }
                });
                alertDialogBuilder.setView(deleteView);
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                setAccounts();
                                adapter.notifyDataSetChanged();
                                drawPie();
                                textView.setText(mParam3+"收支一览");

                            }
                        })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                alertDialog= alertDialogBuilder.create();
                // show it
                alertDialog.show();
            }
        });
        mPieChart=root.findViewById(R.id.pie_chart);
        recyclerView=root.findViewById(R.id.type_accounts);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new MyRecyclerViewAdapter(accounts);
        recyclerView.setAdapter(adapter);
        /*typeView=root.findViewById(R.id.type_view);
        typeView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new AccountFragment.MyRecyclerViewAdapter(accounts);

        typeView.setAdapter(adapter);
        TextView textView=root.findViewById(R.id.LastThreeMonth);*/

        /*textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month= c.get(Calendar.MONTH);
                ArrayList<Account> list;
                for(int i=0;i<3;i++){
                    list= DBManager.SelectByMonth(year,month);
                    accounts.addAll(list);
                    month--;
                }

            }
        });*/
        drawPie();






        return  root;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setAccounts(){
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month= c.get(Calendar.MONTH);
        int date=c.get(Calendar.DATE);
        ArrayList<Account> list;
        ArrayList<Account> new_list=new ArrayList<>();
        if(mParam1.equals("1")){
            if(mParam3.equals("自定义")){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String start= sdf.format(startTime);
                String end= sdf.format(endTime);
                accounts=DBManager.SelectFromTo(start,end,1);
            }
            else if(mParam3.equals("本月")){
                accounts=DBManager.getTypeSum(year,month+1,1);

            }
            else if(mParam3.equals("上月")){
                accounts= DBManager.getTypeSum(year,month,1);
            }
            else if(mParam3.equals("近三个月")){
                accounts=DBManager.getTypeSum(year,month+1,1);
                list=DBManager.getTypeSum(year,month,1);
                accounts.addAll(list);
                list=DBManager.getTypeSum(year,month-1,1);
                accounts.addAll(list);
            }
            else if(mParam3.equals("近六个月")){
                accounts=DBManager.getTypeSum(year,month+1,1);
                list=DBManager.getTypeSum(year,month,1);
                accounts.addAll(list);
                list=DBManager.getTypeSum(year,month-2,1);
                accounts.addAll(list);
                list=DBManager.getTypeSum(year,month-3,1);
                accounts.addAll(list);
                list=DBManager.getTypeSum(year,month-4,1);
                accounts.addAll(list);
                list=DBManager.getTypeSum(year,month-5,1);
                accounts.addAll(list);

            }
            else accounts=DBManager.SelectByYear(year,1);

        }
        else{
            if(mParam3.equals("自定义")){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String start= sdf.format(startTime);
                String end= sdf.format(endTime);
                accounts=DBManager.SelectFromTo(start,end,2);
            }
            else if(mParam3.equals("本月")){
                    accounts=DBManager.getTypeSum(year,month+1,2);

                }
                else if(mParam3.equals("上月")){
                    accounts= DBManager.getTypeSum(year,month,2);
                }
                else if(mParam3.equals("近三个月")){
                    accounts=DBManager.getTypeSum(year,month+1,2);
                    list=DBManager.getTypeSum(year,month,2);
                    accounts.addAll(list);
                    list=DBManager.getTypeSum(year,month-1,2);
                    accounts.addAll(list);
                }
                else if(mParam3.equals("近六个月")){
                    accounts=DBManager.getTypeSum(year,month+1,2);
                    list=DBManager.getTypeSum(year,month,2);
                    accounts.addAll(list);
                    list=DBManager.getTypeSum(year,month-2,2);
                    accounts.addAll(list);
                    list=DBManager.getTypeSum(year,month-3,2);
                    accounts.addAll(list);
                    list=DBManager.getTypeSum(year,month-4,2);
                    accounts.addAll(list);
                    list=DBManager.getTypeSum(year,month-5,2);
                    accounts.addAll(list);

                }
                else accounts=DBManager.SelectByYear(year,2);


        }

        if(mParam2.equals("按分类")){
            Map<String, List<Account>> bmListMap = new HashMap<String, List<Account>>();
            bmListMap = accounts.stream().collect(Collectors.groupingBy(Account -> Account.getType()));
            for (Map.Entry<String, List<Account>> entry : bmListMap.entrySet()) {
                List<Account> currnrtbmList = entry.getValue();
                int sum=0;
                int image=0;
                String da=new String();
                for (Account account:currnrtbmList) {

                    sum+=account.getNumber();
                    image=account.getCoverResourceId();
                    da=account.getDate();
                }
                Account acc=new Account(entry.getKey(),"",sum,image,"");
                acc.setDate(da);
                new_list.add(acc);
            }
        }
        else{
            Map<String, List<Account>> bmListMap = new HashMap<String, List<Account>>();
            bmListMap = accounts.stream().collect(Collectors.groupingBy(Account -> Account.getSource()));
            for (Map.Entry<String, List<Account>> entry : bmListMap.entrySet()) {
                List<Account> currnrtbmList = entry.getValue();
                int sum=0;
                int image=0;
                String da=new String();
                for (Account account:currnrtbmList) {

                    sum+=account.getNumber();
                    try{
                        image=hash.get(account.getSource());
                    }catch (Exception e){
                        image=R.drawable.other;
                    }

                    da=account.getDate();
                }
                Account acc;
                if(entry.getKey().equals(""))
                    acc=new Account("其他账户","",sum,image, entry.getKey());
                else acc=new Account(entry.getKey(),"",sum,image, entry.getKey());
                acc.setDate(da);
                new_list.add(acc);
            }
        }

        accounts=new_list;

    }
    private void drawPie(){
        mPieChart.setUsePercentValues(true); //设置是否使用百分值,默认不显示
        mPieChart.setDragDecelerationFrictionCoef(0.95f);

        //绘制中间文字
        mPieChart.setDrawCenterText(true);

        SpannableString sp;
        if(mParam1.equals("1"))
            sp = new SpannableString("收入饼状图");
        else sp = new SpannableString("支出饼状图");
        mPieChart.setCenterText(sp);
        mPieChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        //设置是否为实心图，以及空心时 中间的颜色
        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        //设置圆环信息
        mPieChart.setTransparentCircleColor(Color.WHITE);//设置透明环颜色
        mPieChart.setTransparentCircleAlpha(110);//设置透明环的透明度
        mPieChart.setHoleRadius(55f);//设置内圆的大小
        mPieChart.setTransparentCircleRadius(60f);//设置透明环的大小

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        //选中变大
        mPieChart.setHighlightPerTapEnabled(true);

        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();


        if(mParam1.equals("1")){
            if(mParam2.equals("按分类")){
                for(Account account:accounts){
                    entries.add(new PieEntry(account.getNumber(),account.getType()));
                }
            }
            else{
                for(Account account:accounts){
                    entries.add(new PieEntry(account.getNumber(),account.getSource()));
                }
            }
        }
        else{
            if(mParam2.equals("按分类")){
                for(Account account:accounts){
                    entries.add(new PieEntry(-1*account.getNumber(),account.getType()));
                }
            }
            else{
                for(Account account:accounts){
                    entries.add(new PieEntry(-1*account.getNumber(),account.getSource()));
                }
            }
        }

        //设置数据
        setData(entries);

        //默认动画
        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置图例
        Legend l = mPieChart.getLegend();
        //设置显示的位置，低版本用的是setPosition();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        //设置是否显示图例
        l.setDrawInside(false);
        l.setEnabled(true);

        // 输入图例标签样式
        mPieChart.setEntryLabelColor(Color.BLUE);
        mPieChart.setEntryLabelTextSize(18f);

    }
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "");
        //设置个饼状图之间的距离
        dataSet.setSliceSpace(0f);
        //颜色的集合，按照存放的顺序显示
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);

        //设置折线
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        //设置线的长度
        dataSet.setValueLinePart1Length(0.3f);
        dataSet.setValueLinePart2Length(0.3f);
        //设置文字和数据图外显示
        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        //百分比设置
        data.setValueFormatter(new PercentFormatter());
        //文字的颜色
        data.setValueTextSize(14f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        // 撤销所有的亮点
        mPieChart.highlightValues(null);
        mPieChart.invalidate();
    }




    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        //private ArrayList<Account> accounts;


        public MyRecyclerViewAdapter(ArrayList<Account> accounts) {

        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_item_holder, parent, false);
            return new MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            MyViewHolder holder =(MyViewHolder)Holder;
            holder.getImageView().setImageResource(accounts.get(position).getCoverResourceId());
            holder.getType().setText(accounts.get(position).getType());
            holder.getNumber().setText(accounts.get(position).getNumber()+"");
            holder.getRemark().setText(accounts.get(position).getRemark());
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder{

            private final ImageView imageView;
            private final TextView type;
            private final TextView remark;
            private final TextView number;


            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.type=view.findViewById(R.id.type);
                this.remark=view.findViewById(R.id.remark);
                this.number=view.findViewById(R.id.number);


            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getType() {
                return type;
            }

            public TextView getRemark() {
                return remark;
            }

            public TextView getNumber() {
                return number;
            }





        }
    }

}